/*
 * @Author: czy
 * @Date: 2021-04-27 19:30:38
 * @LastEditTime: 2021-04-29 16:25:20
 */
#ifndef __EXCEPTION_H_
#define __EXCEPTION_H_
#include "mystdio.h"
#include "mystdlib.h"

typedef struct
{
    unsigned int esp;
    unsigned int ebp;
    unsigned int eip;
    unsigned int edi;
    unsigned int esi;
    
    unsigned int eflags;

    short int CS;
    short int DS;
    short int ES;
    short int SS;
} jmp_buf;

extern int setjmp(jmp_buf *Jump_Buffer);
extern void longjmp(jmp_buf *Jump_Buffer);

void add_jump_buffer_index(int i);
int get_jump_buffer_index(void);
int get_jump_flags(int index);
int set_jump_flags(int index, int value);
jmp_buf *get_jump_buffer(void);
 
#define try add_jump_buffer_index(1);\
            set_jump_flags(get_jump_buffer_index(), setjmp(get_jump_buffer()));\
            if (!get_jump_flags(get_jump_buffer_index()))
#define catch add_jump_buffer_index(-1);\
            if (get_jump_flags(get_jump_buffer_index() + 1))
#define throw int __line__ = __LINE__;\
            char *__file__ = {__FILE__};\
            if (get_jump_buffer_index() >= 0){\
            longjmp(get_jump_buffer());\
            }\
            else {\
            message(LEFT, RED, "Unhandle exception: at %s, line %d", __file__, __line__);\
            myExit(-1);\
            }
#endif